package com.customization.unionpay.contract.serivce.impl;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.contract.dao.BaseContractSynDataDao;
import com.customization.unionpay.contract.dao.ContractLedgerDao;
import com.customization.unionpay.contract.serivce.IContractDataSynService;
import com.customization.unionpay.contract.util.ContractWorkflowServiceUtils;
import com.engine.core.impl.Service;
import weaver.conn.RecordSet;
import weaver.hrm.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IContractDataSynServiceImpl extends Service implements IContractDataSynService {

    private static final Log logger = LogFactory.getLog(IContractDataSynServiceImpl.class);

    String SRHTTZTableName = "uf_skhttz"; //收入合同台账表名
    String ZCHTTZTableName = "uf_zchttz"; //支出合同台账表名

    // 合同收付款关系: 收款合同
    private static final int HTSFKGX_SKHT = 1;
    // 合同收付款关系: 付款合同
    private static final int HTSFKGX_FKHT = 2;
    // 合同收付款关系: 收付款合同
    private static final int HTSFKGX_SFKHT = 3;
    // 合同收付款关系: 合作协议（非收付款合同)
    private static final int HTSFKGX_HZXY = 4;


    @Override
    public boolean addbaseContract(JSONObject json, User user) {
        Integer htsfkgx = json.getIntValue("payRelation");
        // 记录合同中心推送记录表
        Map dataLog = getSynDataLogFromJson(json);
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        int insertflag = baseContractSynDataDao.addContractDataSynData(dataLog);

        if(insertflag > 0) {
            switch (htsfkgx){
                case HTSFKGX_SKHT: //1：收款合同
                    ContractWorkflowServiceUtils.createWorkflowOfSKHTBA(json,user);
                    break;
                case HTSFKGX_FKHT: //2：付款合同
                    ContractWorkflowServiceUtils.createWorkflowOfFKHTBA(json,user);
                    break;
                case HTSFKGX_SFKHT://3：收付款合同
                    ContractWorkflowServiceUtils.createWorkflowOfSZHTBA(json,user);
                    break;
                case HTSFKGX_HZXY://4：合作协议（非收付款合同）
                    ContractWorkflowServiceUtils.createWorkflowOfFKHTBA(json,user);
                    break;
                default:
                    return false;
            }
        }
        return true;
    }

    /**
     * 变更
     * 常规支出合同变更备案审批（补充合同）
     * 收入合同变更备案审批（补充合同）
     * @param contractNumber
     * @return
     */
    @Override
    public boolean changeFilingProcess(String contractNumber) {
        // 查询合同
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        // 查询合同信息
        Map<String,String> contractBaseInfo = baseContractSynDataDao.selectContractBaseInfoByCntractNumber(contractNumber);

        if(null == contractBaseInfo){
            return false;
        }
        JSONObject htmx = null;
        String htsfkgx = contractBaseInfo.get("htsfkgx");
        if( "1".equals(htsfkgx)) {
            // 收款合同 (htsfkgx = 1)
            htmx = selectSKHTMX(contractNumber);

        }else {
            // 付款合同 (htsfkgx = 2)
            htmx = selectFKHTMX(contractNumber);
        }
        Map<String,String> map = new HashMap<>();
        map.putAll(contractBaseInfo);
        return ContractWorkflowServiceUtils.createWorkflowOfHTBGBA(map,htmx);
    }

    /**
     * 查询收款合同明细
     * @param htbh
     * @return
     */
    private JSONObject selectSKHTMX(String htbh) {

        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        JSONObject mx1 = baseContractSynDataDao.selectSKContractMX(htbh,1);
        JSONObject mx2 = baseContractSynDataDao.selectSKContractMX(htbh,2);

        mx1.putAll(mx2);
        return mx1;
    }

    /**
     * 查询付款合同明细
     * @param htbh
     * @return
     */
    private JSONObject selectFKHTMX(String htbh) {
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        JSONObject mx1 = baseContractSynDataDao.selectFKContractMX(htbh,1);
        JSONObject mx2 = baseContractSynDataDao.selectFKContractMX(htbh,2);

        mx1.putAll(mx2);
        return mx1;
    }

    /**
     * 移交
     * 收入合同移交
     * 支出合同移交
     * @param jsonObject
     * @return
     */
    @Override
    public boolean contractTransfer(JSONObject jsonObject) {

        String contractNumber = jsonObject.getString("contractNumber");
        String transferType = jsonObject.getString("transferType");
        String transferReason = jsonObject.getString("transferReason");
        Integer xhtjbryxm = jsonObject.getInteger("newUser");
        User user = new User(xhtjbryxm);
        String xhtjbjgmc = user.getUserSubCompany1()+"";
        String xhtjbbmmc = user.getUserDepartment()+"";
        // 查询合同
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        Map<String,String> contractBaseInfo = baseContractSynDataDao.selectYJContractBaseInfoByCntractNumber(contractNumber);

        if(null != contractBaseInfo) {
            Map<String, String> map = new HashMap<>();
            map.putAll(contractBaseInfo);
            // 移交类型
            map.put("yjlx", transferType);
            // 移交原因
            map.put("yjyy", transferReason);
            // 新合同经办机构名称
            map.put("xhtjbjgmc",xhtjbjgmc);
            //新合同经办部门名称
            map.put("xhtjbbmmc",xhtjbbmmc);
            //新合同经办人员姓名
            map.put("xhtjbryxm",xhtjbryxm+"");
            String htsfkgx = map.get("htsfkgx");
            if( "1".equals(htsfkgx)){
                // 收款合同 (htsfkgx = 1)
                baseContractSynDataDao.skContractTransfer(contractNumber,xhtjbryxm,xhtjbjgmc,xhtjbbmmc);
            }else {
                // 付款合同 (htsfkgx = 2)
                baseContractSynDataDao.fkContractTransfer(contractNumber,xhtjbryxm,xhtjbjgmc,xhtjbbmmc);
            }
            return true;
        }else {
            return false;
        }
    }

    /**
     * 关闭
     * @param bodyJson
     * @return
     */
    @Override
    public boolean contractClose(JSONObject bodyJson,User user) {
        String contractNumber = bodyJson.getString("contractNumber");
        String closeReason = bodyJson.getString("closeReason");
        String annexs = bodyJson.getString("annexs");
        // 查询合同
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        Map<String,String> contractBaseInfo = baseContractSynDataDao.selectGBContractBaseInfoByCntractNumber(contractNumber);

        if(null != contractBaseInfo) {
            String htzt = contractBaseInfo.get("htzt");
            if(!"2".equals(htzt)){
                return false;
            }
            Map<String, Object> map = new HashMap<>();
            map.putAll(contractBaseInfo);
            map.put("htgbsm", closeReason);
            map.put("xgfj", annexs);

            baseContractSynDataDao.contractClose(contractNumber);
            return true;
        }else {
            return false;
        }
    }

    @Override
    public JSONObject contractInfo(List<String> contractNumbers,Integer contract,Integer page,Integer pageSize,User user) {
        JSONObject result = null;
        ContractLedgerDao contractLedgerDao = new ContractLedgerDao();
        switch (contract) {
            case HTSFKGX_SKHT: //1：收款合同
                result = contractLedgerDao.selectSKContractInfoByCntractNumber(SRHTTZTableName,contractNumbers,page,pageSize);
                break;
            case HTSFKGX_FKHT: //2：付款合同
            case HTSFKGX_SFKHT://3：收付款合同
            case HTSFKGX_HZXY://4：合作协议（非收付款合同）
                result = contractLedgerDao.selectZCContractInfoByCntractNumber(ZCHTTZTableName,contractNumbers,page,pageSize);
                break;
            default:
                return null;
        }
        return result;
    }

    @Override
    public boolean contractLedger(Integer formId, Integer requestId) {
        //流程主表
        String mainTableName = "";
        String detailTableName = "";
        // 获取合同类型
        String sql = "select htsfkgx,htbh from " + mainTableName + " where requestId="+requestId;
        RecordSet recordSet = new RecordSet();
        recordSet.execute(sql);
        if(recordSet.next()){
            int htsfkgx = recordSet.getInt("htsfkgx");
            switch (htsfkgx) {
                case HTSFKGX_SKHT: //1：收款合同
                    detailTableName = mainTableName + "_dt2";
                    addSKContractLedgerByRequestId(requestId,mainTableName,detailTableName);
                    break;
                case HTSFKGX_FKHT: //2：付款合同
                case HTSFKGX_HZXY://4：合作协议（非收付款合同）
                    detailTableName = mainTableName + "_dt2";
                    addFKContractLedgerByRequestId(requestId,mainTableName,detailTableName);
                    break;
                case HTSFKGX_SFKHT://3：收付款合同
                    addSFKContractLedger(requestId,mainTableName,detailTableName);
                    break;
                default:
                    return false;
            }
        }
        return true;
    }

    /**
     * 校验签约方
     * @param bodyJson
     * @return
     */
    @Override
    public Map<String, Object> checkSigner(JSONObject bodyJson) {
//        AssociationService associationservice =new AssociationServiceImpl();
        Map<String,Object> res = new HashMap<>();
//        JSONArray signerJson = bodyJson.getJSONArray("signingParties");
//        if(signerJson == null ){
//            res.put("status",false);
//            return res;
//        }
//        Map<String, Object> params;
//        for (int i = 0; i < signerJson.size(); i++) {
//            JSONObject json = signerJson.getJSONObject(i);
//            //签约方名称
//            String qyfmc = json.getString("qyfmc");
//            //签约方校验
//            params = new HashMap<>();
//            params.put("keyword",qyfmc);
//            Map<String,Object> signerRes = associationservice.checkKeyword(params);
//            if ((Boolean)signerRes.get("status")) {
//                res.put("status",true);
//                json.put("qyfmc",Integer.parseInt(signerRes.get("id").toString()));
//            }else{
//                res.putAll(signerRes);
//                return res;
//            }
//        }
        return res;
    }

    /**
     * 记录收付款合同台账
     * @param requestId
     * @param mainTableName
     * @param detailTableName
     * @return
     */
    private boolean addSFKContractLedger(Integer requestId,String mainTableName,String detailTableName) {
        // 处理收款逻辑
        addSKContractLedger(requestId,mainTableName,detailTableName);
        // 处理付款逻辑
        addSFKContractFKLedger(requestId);
        return true;
    }

    /**
     * 处理收付款合同收款逻辑
     * @param htbh
     * @return
     */
    private boolean addSFKContractSKLedger(String htbh) {
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        // 查询合同主表信息
        Map skContractMain = baseContractSynDataDao.selectSFKContractSKMain(htbh);
        // 查询合同明细表信息
        List<Map> skjhContractMX = baseContractSynDataDao.selectSFKJHContractSKMX(htbh);
        // 插入付款合同台账信息
        baseContractSynDataDao.addZCContractDataLog(skContractMain);
        // 添加主表信息
        Map main = new HashMap();
        main.put("htmc",skContractMain.get("htmc"));
        main.put("htbh",skContractMain.get("htbh"));
        main.put("htfkysbde",skContractMain.get("htfkysbde"));
        main.put("htzt",skContractMain.get("htzt"));

        baseContractSynDataDao.addSKJHContractDataLog(main,skjhContractMX);
        return true;
    }

    /**
     * 处理收付款合同付款逻辑
     * @param requestId
     * @return
     */
    private boolean addSFKContractFKLedger(Integer requestId) {
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        // 查询合同主表信息
        Map fkContractMain = baseContractSynDataDao.selectSFKContractFKMainByRequestId(requestId);
        // 查询合同明细表信息
        List<Map> fkjhContractMX = baseContractSynDataDao.selectSFKJHContractFKMXByRequestId(requestId);
        // 插入付款合同台账信息
        baseContractSynDataDao.addZCContractDataLog(fkContractMain);
        String htbh = fkContractMain.get("htbh")+"";
        String id = baseContractSynDataDao.selectZchttzIdByHtbh(htbh);
        // 添加主表信息
        Map main = new HashMap();
        main.put("sfjcht",fkContractMain.get("sfjcht"));
        main.put("htmc",fkContractMain.get("htmc"));
        main.put("htbh",id);
        main.put("htfkysbde",fkContractMain.get("htfkysbde"));
        main.put("htzt",fkContractMain.get("htzt"));
        main.put("htglbhwb",id);

        baseContractSynDataDao.addZCJHContractDataLog(main,fkjhContractMX);

        return true;
    }

    /**
     * 记录付款合同台账
     * @param requestId
     * @param mainTableName
     * @param detailTableName
     * @return
     */
    private boolean addFKContractLedgerByRequestId(Integer requestId,String mainTableName,String detailTableName) {
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        // 查询合同主表信息
        Map fkContractMain = baseContractSynDataDao.selectFKContractMainByRequestId(requestId,mainTableName);
        // 查询合同明细表信息
        List<Map> fkjhContractMX = baseContractSynDataDao.selectFKJHContractMXByRequestId(requestId,mainTableName,detailTableName);
        // 插入合同台账信息
        fkContractMain.put("htbalc",requestId);
        fkContractMain.put("htglbh",fkContractMain.get("htbh"));
        Integer htId = baseContractSynDataDao.addZCContractDataLog(fkContractMain);
        //插入签约方信息
        List<Map> signatories = baseContractSynDataDao.selectFKHTSignatoriesByRequestId(requestId,mainTableName);
        addFKContractSignatories(htId,signatories);

        // 添加付款计划明细
        Map main = new HashMap();
        main.put("sfjcht",fkContractMain.get("sfjcht"));
        main.put("htmc",fkContractMain.get("htmc"));
        main.put("htbh",htId);
        main.put("htfkysbde",fkContractMain.get("htfkysbde"));
        main.put("htzt",fkContractMain.get("htzt"));
        main.put("htglbhwb",fkContractMain.get("htbh"));
        main.put("htglbh",htId);

        baseContractSynDataDao.addZCJHContractDataLog(main,fkjhContractMX);
        return true;
    }

    private boolean addFKContractSignatories(Integer mainId, List<Map> signatories) {
        BaseContractSynDataDao dataDao = new BaseContractSynDataDao();
        for(int i = 0; i < signatories.size();i++){
            Map map = signatories.get(i);
            map.put("mainid",mainId);
            dataDao.addFKContractSigatoriesData(map);
        }
        return true;
    }

    /**
     * 记录收款合同台账
     * @param requestId
     * @param mainTableName
     * @param detailTableName
     * @return
     */
    private boolean addSKContractLedger(Integer requestId,String mainTableName,String detailTableName) {
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        // 查询合同主表信息
        Map skContractMain = baseContractSynDataDao.selectSKContractMainByRequestId(mainTableName,requestId);
        // 查询合同明细表信息
        List<Map> skjhContractMX = baseContractSynDataDao.selectSKJHContractMXByRequestId(requestId,mainTableName,detailTableName);
        // 插入合同台账信息
        baseContractSynDataDao.addSKContractDataLog(skContractMain);
        String htbh = skContractMain.get("htbh")+"";
        String id = baseContractSynDataDao.selectSrhttzIdByHtbh(htbh);
        // 添加主表信息
        Map main = new HashMap();
        main.put("htbalc",requestId);
        main.put("htmc",skContractMain.get("htmc"));
        main.put("htbh",id);
        main.put("htfkysbde",skContractMain.get("htfkysbde"));
        main.put("htzt",skContractMain.get("htzt"));

        baseContractSynDataDao.addSKJHContractDataLog(main,skjhContractMX);
        return true;
    }

    private boolean addSKContractLedgerByRequestId(Integer requestId,String mainTableName,String detailTableName) {
        BaseContractSynDataDao baseContractSynDataDao = new BaseContractSynDataDao();
        // 查询合同主表信息
        Map skContractMain = baseContractSynDataDao.selectSKContractMainByRequestId(mainTableName,requestId);
        // 查询合同明细表信息
        List<Map> skjhContractMX = baseContractSynDataDao.selectSKJHContractMXByRequestId(requestId,mainTableName,detailTableName);
        // 插入合同台账信息
        skContractMain.put("htglbh",skContractMain.get("htbh"));
        Integer htId = baseContractSynDataDao.addSKContractDataLog(skContractMain);
        List<Map> signatories = baseContractSynDataDao.selectSKHTSignatoriesByRequestId(requestId,mainTableName);
        // 插入签约方明细
        addSKContractSignatories(htId,signatories);
        // 添加收入计划
        Map main = new HashMap();
        main.put("htmc",skContractMain.get("htmc"));
        main.put("htskysbde",skContractMain.get("htskysbde"));
        main.put("htzt",skContractMain.get("htzt"));
        main.put("htwb",skContractMain.get("htwb"));
        main.put("htbh",htId);
        main.put("htglbh",htId);
        baseContractSynDataDao.addSKJHContractDataLog(main,skjhContractMX);
        return true;
    }

    private boolean addSKContractSignatories(Integer mainId, List<Map> signatories) {
        BaseContractSynDataDao dataDao = new BaseContractSynDataDao();
        for(int i = 0; i < signatories.size();i++){
            Map map = signatories.get(i);
            map.put("mainid",mainId);
            dataDao.addSKContractSigatoriesData(map);
        }
        return true;
    }


    private Map getSynDataLogFromJson(JSONObject json) {
        Map result = new HashMap();
        List<String> paramList = new ArrayList<>(json.keySet());
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("contractName","htmc");
        paramMap.put("contractNumber","htbh");
        paramMap.put("contractOrg","htjbjgmc");
        paramMap.put("contractDept","htjbbmmc");
        paramMap.put("contractUser","htjbryxm");
        paramMap.put("contractFilingDate","htgdr");
        paramMap.put("contractSignDate","htqdsj");
        paramMap.put("contractExpireDate","htdqr");
        paramMap.put("contractPresetAmount","htskysbde");
        paramMap.put("attachment","yyyhtfj");
        paramMap.put("contractMainNum","zhtbh");
        paramMap.put("relatedMainNum","glzht");
        paramMap.put("remark","htlsbz");
        paramMap.put("payRelation","htsfkgx");
        paramMap.put("contractBusiType","htywlx");
        paramMap.put("receivableChangeRecordPresetAmount","srhtbghtfkysbde");
        paramMap.put("expendRecordPresetAmount","zchthtfkysbde");
        paramMap.put("expendRecordCollectiveProcurement","zchtsfjcht");
        paramMap.put("expendRecordMultiDepartment","zchtsfsjdbmzhsfkjh");
        paramMap.put("expendRecordAbstract","zchthtlszygy");
        paramMap.put("expendChangeRecordPresetAmount","zchtbahtfkysbde");
        paramMap.put("expendChangeRecordCollectiveProcurement","zchtbasfjcht");
        paramMap.put("expendChangeRecordMultiDepartment","zchtbasfsjdbmzhsfkjh");
        paramMap.put("expendChangeRecordAbstract","zchtbahtlszygy");

        for (String param : paramList){
            String key = paramMap.get(param);
            if(null != key && !"".equals(key)){
                result.put(key,json.get(param));
            }
        }
        return result;

    }

    private Map<String,Object> getSynDataFromJson(JSONObject json){
        Map result = new HashMap();
        List<String> paramList = new ArrayList<>(json.keySet());
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("contractName","htmc");
        paramMap.put("contractNumber","htbh");
        //--------------------
        paramMap.put("contractOrg","htjbjg");
        paramMap.put("contractDept","htjbbm");
        paramMap.put("contractUser","htjbr");
        //--------------------
        paramMap.put("contractFilingDate","htgdr");
        paramMap.put("contractSignDate","htqdsj");
        paramMap.put("contractExpireDate","htdqr");
        paramMap.put("contractPresetAmount","htskysbde");
        paramMap.put("attachment","yyyhtfj");
        paramMap.put("contractMainNum","zhtbh");
        paramMap.put("relatedMainNum","glzht");
        paramMap.put("remark","htlsbz");
        paramMap.put("payRelation","htsfkgx");
        paramMap.put("contractBusiType","htywlx");

        paramMap.put("receivableChangeRecordPresetAmount","htfkysbde");
        paramMap.put("expendRecordPresetAmount","htfkysbde");
        paramMap.put("expendRecordCollectiveProcurement","sfjc");
        paramMap.put("expendRecordMultiDepartment","sfsjdbmzhsfkjh");
        paramMap.put("expendRecordAbstract","htlsbz");
        paramMap.put("expendChangeRecordPresetAmount","htfkysbde");
        paramMap.put("expendChangeRecordCollectiveProcurement","sfjc");
        paramMap.put("expendChangeRecordMultiDepartment","sfsjdbmzhsfkjh");
        // paramMap.put("expendChangeRecordAbstract","zcbabghtlszygy");

        for (String param : paramList){
            String key = paramMap.get(param);
            if(null != key && !"".equals(key)){
                result.put(key,json.get(param));
            }
        }
        return result;
    }

    private Map<String,String> zchtbaTest(){
        Map result = new HashMap();
//        合同名称	htmc
//        合同编号	htbh
//        合同经办机构	htjbjg
//        合同经办部门	htjbbm
//        合同经办人	htjbr
//        合同归档日	htgdr
//        合同签订时间	htqdsj
//        合同到期日	htdqr
//        合同收款预设标的额	htskysbde
//        合同付款预设标的额	htfkysbde
//        已用印合同附件	yyyhtfj
//        主合同编号	zhtbh
//        关联主合同	glzht
//        是否集采合同	sfjcht
//        是否涉及多部门执行收付款计划	sfsjdbmzhsfkjh
//        合同律审摘要概要	htlszygy
//        合同律审备注	htlsbz
//        合同收付款关系	htsfkgx
//        合同业务类型	htywlx
        result.put("htmc","合同名称"+System.currentTimeMillis());
        result.put("htbh","HTBH"+System.currentTimeMillis());
        result.put("htjbjg","1");
        result.put("htjbbm","3");
        result.put("htjbr","22");
        result.put("htgdr","2024-05-30");
        result.put("htqdsj","2024-01-30");
        result.put("htdqr","2025-07-30");
        result.put("htskysbde","1100");
        result.put("htfkysbde","1200");
//        result.put("yyyhtfj","已用印合同附件");
//        result.put("zhtbh","14");
//        result.put("glzht","15");
//        result.put("sfjcht","16");
//        result.put("sfsjdbmzhsfkjh","17");
//        result.put("htlszygy","18");
//        result.put("htlsbz","19");
//        result.put("htsfkgx","20");
//        result.put("htywlx","21");
        return result;
    }


}
